﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Criterion;
using SinBiota.Model.Entities;
using SinBiota.Model.Persistence.ComplexQueries.Interfaces;

namespace SinBiota.Model.Persistence.ComplexQueries.Implementation
{
    public class RepositoryStatistics : IRepositoryStatistics
    {
        private readonly ISession _session;
        
        public RepositoryStatistics(ISession session)
        {
            _session = session;
        }
        public int TotalofEntity<T>() where T : BaseEntity
        {
            var criteria = _session.CreateCriteria<T>().SetProjection(Projections.RowCount());
            return (int)criteria.UniqueResult();
        }

        public IDictionary<TProperty, int> CountEntityGroupByProperty<TEntity, TProperty>(string property) where TEntity : BaseEntity
        {
            // Get a list of pairs (int, TProperty). One pair for each TProperty different value, with the count of TEntity entities that have that value;
            var criteria = _session.CreateCriteria<TEntity>().SetProjection(
                    Projections.ProjectionList().Add(Projections.RowCount(), "count").Add(
                        Projections.GroupProperty(property))).AddOrder(Order.Desc("count"));
            // transform the result in a dictionary, removing nulls:
            return criteria.List<Object[]>().Where(x => x[1] != null).ToDictionary(x => (TProperty) x[1], x => (int) x[0]);
        }
    }
}